package com.VancouverTongue.VancouverTongue;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.VancouverTongue.bean.*;
import com.VancouverTongue.database.DataManager;
import com.VancouverTongue.database.HelpObj;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private final static String GO_ERROR = "redirect:/error";

	/**
	 * redirect to root
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index() {
		// String s = IdentifyImage.generateImage();

		return "redirect:/";
	}

	@RequestMapping(value = "/Contact", method = RequestMethod.GET)
	public String contact(HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Helper.lastVisit(request, session);
		
		model.addAttribute("RandomRest", DataManager.getRandomRestaurant());
		
		return "Contact";
	}

	/**
	 * root page / index
	 * 
	 * @throws SQLException
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String root(HttpServletRequest request, HttpSession session,
			Model model) throws SQLException {
		Helper.lastVisit(request, session);
		model.addAttribute("registerSucc", session.getAttribute("registerSucc"));
		session.removeAttribute("registerSucc");
		model.addAttribute("alertBox", session.getAttribute("alertBox"));
		session.removeAttribute("alertBox");
		model.addAttribute("catList", DataManager.getCategoryList());

		model.addAttribute("recomLatest", DataManager.getSixLatestRestaurant());
		model.addAttribute("recomTop", DataManager.getSixTopRestaurant());
		model.addAttribute("recomSponsor", DataManager.getSixTopRestaurant());

		return "index";
	}

	/**
	 * check login, POST only, redirect back to previous page if log in OK, else
	 * go error page
	 * 
	 * @throws SQLException
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String userId, String password, HttpSession session)
			throws SQLException {

		String lastVisit = (String) session.getAttribute("lastVisit");
		Account account = DataManager.login(userId, password);

		// user id and password confirm
		if (account != null) {

			Block block = DataManager.getBlock(account.getUserId());
			// user blocked
			if (block != null) {
				Helper.errorMessage(session, "You are block",
						block.getMessage());
				return GO_ERROR;
			}
			session.setAttribute("account", account);

			if (lastVisit == null) {
				return "redirect:/";
			} else {
				return "redirect:" + lastVisit;
			}
		} else {
			Helper.errorMessage(session, "Login failed", "please try again");
			return GO_ERROR;

		}
	}

	/**
	 * log out
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public String logout(HttpSession session) {
		session.removeAttribute("account");
		return "redirect:" + (String) session.getAttribute("lastVisit");
	}

	/**
	 * error page
	 */
	@RequestMapping(value = "/error", method = RequestMethod.GET)
	public String error(HttpSession session, Model model) {
		// model.addAttribute("errorTitle", session.getAttribute("errorTitle"));
		// model.addAttribute("errorBody", session.getAttribute("errorBody"));
		// model.addAttribute("lastVisit", session.getAttribute("lastVisit"));
		//

		return "error";
	}

	/**
	 * view a single Restaurant page
	 * 
	 * @return "restaurant.jsp"
	 * @throws SQLException
	 */
	@RequestMapping(value = "/restaurant/{id}", method = RequestMethod.GET)
	public String viewRestaurant(@PathVariable int id, HttpSession session,
			Model model, HttpServletRequest request) throws SQLException {

		String ALertBox = (String) session.getAttribute("alertBox");
		session.removeAttribute("alertBox");
		model.addAttribute("ALertBox", ALertBox);

		Restaurant restaurant = null;
		restaurant = DataManager.getRestByRestId(id);
		if (restaurant == null) { // page not exist
			return null;
		} else {
			Helper.lastVisit(request, session);

			Helper.passData("account", session, model);

			model.addAttribute("restaurant", restaurant);
			model.addAttribute("commentList",
					DataManager.getCommentByRestId(id));

			int rating = -1;
			Account account = (Account) session.getAttribute("account");
			if (account != null) {
				rating = DataManager.getRating(account.userId, id);
			}

			model.addAttribute("userRating", new Integer(rating));
			model.addAttribute("RandomRest", DataManager.getRandomRestaurant());
			return "restaurant";
		}
	}

	
	@RequestMapping(value = "/restaurant/{id}/edit", method = RequestMethod.GET)
	public String editRestaurant(@PathVariable int id, HttpSession session,
			Model model, HttpServletRequest request) throws SQLException {
		session.setAttribute("CatList", DataManager.getCategoryList());
		Restaurant restaurant;
		restaurant = DataManager.getRestByRestId(id);

		if (restaurant == null) { // page not exist
			return null;
		} else {

			if (!Helper.isLogin(session)) {
				Helper.errorMessage(session, "Log in required",
						"Please login before editing an restaurant");
				return GO_ERROR;
			}

			Helper.lastVisit(request, session);
			session.setAttribute("restaurant", restaurant);

			return "restaurantEdit";
		}
	}

	@RequestMapping(value = "/restaurant/{id}/addComment", method = RequestMethod.POST)
	public String addComment(@PathVariable int id, Comment comment,
	/* String priceText, */HttpSession session) throws SQLException {
		Account account = (Account) session.getAttribute("account");
		if (account == null) {
			Helper.errorMessage(session, "Log in required to leave message",
					"Please login");
			return GO_ERROR;
		}

		if (comment.message.length() == 0) {
			Helper.errorMessage(session, "Empty comment",
					"Please write something");
			return GO_ERROR;
		}

		/*
		 * // invalid price double price = -1; if (priceText.length() > 0) { try
		 * { price = Double.valueOf(priceText); } catch (Exception e) {
		 * Helper.errorMessage(session, "Invalid price value",
		 * "Please enter an valid price value"); return GO_ERROR; } }
		 * comment.price = price;
		 */
		comment.userId = account.getUserId();
		comment.restaurantId = id;
		//comment.message = HelpObj.HTMLcheck(comment.message);
		DataManager.addComment(comment);
		return "redirect:" + (String) session.getAttribute("lastVisit");
	}

	
	/**
	 * add a request to edit restaurant
	 * 
	 * @throws SQLException
	 */
	@RequestMapping(value = "/restaurant/{id}/addRequest", method = RequestMethod.POST)
	public String editRestaurantRequest(@PathVariable int id, Model model,
			RestaurantRequest request, HttpSession session) throws SQLException {
		String alertBox = "";
		Account account = (Account) session.getAttribute("account");
		model.addAttribute("catList", DataManager.getCategoryList());
		

		String error = "<ul><li>This field is required.</li></ul>";
		if (request.restaurantName.compareTo("") == 0
				|| request.phone.compareTo("") == 0
				|| request.streetName.compareTo("") == 0
				|| request.city.compareTo("") == 0
				|| request.description.compareTo("") == 0
				|| request.businessHour.compareTo("") == 0
				|| Integer.toString(request.categoryCode).compareTo("") == 0) {
			if (request.restaurantName.compareTo("") == 0) {
				model.addAttribute("restaurantName", error);
			}
			if (request.phone.compareTo("") == 0) {
				model.addAttribute("phone", error);
			}
			if (request.streetName.compareTo("") == 0) {
				model.addAttribute("streetName", error);
			}
			if (request.city.compareTo("") == 0) {
				model.addAttribute("city", error);
			}
			if (request.description.compareTo("") == 0) {
				model.addAttribute("description", error);
			}
			if (request.businessHour.compareTo("") == 0) {
				model.addAttribute("businessHour", error);
			}
			if (Integer.toString(request.categoryCode).compareTo("") == 0) {
				model.addAttribute("categoryCode", error);
			}
			// model.addAttribute("RestaurantName", req.getRestaurantName());
			// model.addAttribute("Phone", req.getPhone());
			// model.addAttribute("StreetName", req.getStreetName());
			// model.addAttribute("City", req.getCity());
			// model.addAttribute("Description", req.getDescription());
			// model.addAttribute("BusinessHour", req.getBusinessHour());
			// model.addAttribute("CategoryCode", req.getCategoryCode());
			// model.addAttribute("Website", req.getWebsite());
			// model.addAttribute("Image", req.getImage());
			// model.addAttribute("restaurantId",req.restaurantId);
			// model.addAttribute("restaurant",req);
			// ArrayList<Category> cList=DataManager.getCategoryList();
			// for(Category c:cList){
			// System.out.println("cat="+c.getName());
			// }
			session.setAttribute("restaurant", request);
			session.setAttribute("CatList", DataManager.getCategoryList());
			return "redirect:/restaurant/" + id + "/edit";
		} else {
			if (request.image.compareTo("") == 0) {
				request.image = "/VancouverTongue/static/defaultRestaurant.png";
			}
			if (account.level >= 3) {
				DataManager.editRestaurant(request);
				alertBox = "<script>alert('RESTAURANT HAS SUCCESSFULLY BEEN ADDED')</script>";
				session.setAttribute("alertBox", alertBox);
			} else {
				request.editBy = account.getUserId();
				request.actId = 2;
				DataManager.addRequest(request);
				alertBox = "<script>alert('REQUEST HAS BEEN SENT TO OUR STAFF, PLEASE WAIT')</script>";
				session.setAttribute("alertBox", alertBox);
			}
			return "redirect:/restaurant/" + id;
		}

	}

	/**
	 * rate a restaurant
	 * 
	 * @throws SQLException
	 */
	@RequestMapping(value = "/restaurant/{id}/addRating", method = RequestMethod.POST)
	public String rateRestaurant(@PathVariable int id, int rating,
			HttpSession session) throws SQLException {
		Account account = (Account) session.getAttribute("account");
		if (account == null) {
			Helper.errorMessage(session, "Log in required",
					"Please login before editing");
			return GO_ERROR;
		}

		DataManager.addRating(account.userId, id, rating);

		return "redirect:/restaurant/" + id;
	}

	/**
	 * delete a comment
	 * 
	 * @throws SQLException
	 */
	@RequestMapping(value = "/restaurant/{id}/deleteComment", method = RequestMethod.POST)
	public String deleteComment(@PathVariable int id, int commentId,
			HttpSession session) throws SQLException {
		Account account = (Account) session.getAttribute("account");
		if (account == null) {
			Helper.errorMessage(session, "Log in required",
					"Please login before editing");
			return GO_ERROR;
		}
		String author = DataManager.getCommentAuthor(commentId);
		if (author == null) {
			return "redirect:/restaurant/" + id;
		}

		if (account.level < 3 && !account.userId.equals(author)) {
			Helper.errorMessage(session, "Permission denied",
					"You don't have authoriation of doing this");
			return GO_ERROR;
		}
		DataManager.deleteOneComment(commentId);

		return "redirect:/restaurant/" + id;
	}

	/**
	 * Change email
	 * @param userId
	 * @param email
	 * @param session
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/{userId}/email", method = RequestMethod.POST)
	public String changeEmail(@PathVariable String userId, String email,
			HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Helper.lastVisit(request, session);
		Account account = DataManager.getAccountByUserId(userId);
		if(email == null || email.compareTo("")==0){
//			model.addAttribute("account", account);
//			Account loginAccount = (Account) session.getAttribute("account");
//			if (loginAccount != null
//					&& account.userId.endsWith(loginAccount.userId)) {
//				model.addAttribute("edit", new Boolean(true));
//			} else {
//				model.addAttribute("edit", new Boolean(false));
//			}
			String emailError = "*Email required";
			model.addAttribute("emailError", emailError);
			return "profile";
		}
		DataManager.editAccEmail(userId, email);
		return "redirect:/index";
	}
	
	
	/**
	 * Change password
	 * @param userId
	 * @param oldPassword
	 * @param newPassword
	 * @param confirmPassword
	 * @param session
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/{userId}/password", method = RequestMethod.POST)
	public String changePassword(@PathVariable String userId, String oldPassword,
			String newPassword, String confirmPassword,
			HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Account account = DataManager.getAccountByUserId(userId);
		if(oldPassword.compareTo(account.password)!=0){
			model.addAttribute("passwordError", "*Password Incorrect");
			return "profile";
		}
		if(newPassword.compareTo("")==0){
			model.addAttribute("newPasswordError", "*New Password required");
			return "profile";
		}
		if(confirmPassword.compareTo("")==0){
			model.addAttribute("confirmPasswordError", "*Confirm Password required");
			return "profile";
		}
		if(confirmPassword.compareTo(newPassword)!=0){
			model.addAttribute("unmatchedError", "*New Password unmatched");
			return "profile";
		}
		DataManager.editAccPassword(userId, newPassword);
		session.removeAttribute("account");
		return "redirect:/index";
	}
	
	@RequestMapping(value = "/{userId}/description", method = RequestMethod.POST)
	public String changeDescription(@PathVariable String userId, String description,
			HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Account account = DataManager.getAccountByUserId(userId);
		if(description == null || description.compareTo("")==0){
//			model.addAttribute("account", account);
//			Account loginAccount = (Account) session.getAttribute("account");
//			if (loginAccount != null
//					&& account.userId.endsWith(loginAccount.userId)) {
//				model.addAttribute("edit", new Boolean(true));
//			} else {
//				model.addAttribute("edit", new Boolean(false));
//			}
//			String emailError = "*Email required";
			model.addAttribute("descriptionError", "*Description Required");
			return "profile";
		}
		DataManager.editAccDescription(userId, description);
		return "redirect:/index";
	}
	
	/**
	 * view a profile
	 * 
	 * @throws SQLException
	 */
	@RequestMapping(value = "/profile", method = RequestMethod.GET)
	public String viewProfile(@RequestParam("userId") String userId,
			HttpSession session, Model model, String oldPassword,
			String newPassword, String confirmPassword, Account a,
			HttpServletRequest request) throws SQLException {

		Account viewAccount = DataManager.getAccountByUserId(userId);
		if (viewAccount == null) {
			return null;
		}
		model.addAttribute("account", viewAccount);
		Account loginAccount = (Account) session.getAttribute("account");
		if (loginAccount != null
				&& viewAccount.userId.endsWith(loginAccount.userId)) {
			model.addAttribute("edit", new Boolean(true));
		} else {
			model.addAttribute("edit", new Boolean(false));
		}


		model.addAttribute("RandomRest", DataManager.getRandomRestaurant());
		return "profile";
	}

	
	
	
	/**
	 * submit a "add restaurant action"
	 * 
	 * @param rest
	 * @param session
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
//TODO
	@RequestMapping(value = "/addRestaurant/temp", method = RequestMethod.GET)
	public String addRestaurantData(RestaurantRequest rest,
			HttpSession session, Model model, HttpServletRequest request)
			throws SQLException {
		String alertBox = "";
		Account account = (Account) session.getAttribute("account");
		RestaurantRequest req = new RestaurantRequest();
		req.ownerId = rest.getOwnerId();
		req.restaurantId = rest.restaurantId;
		req.restaurantName = rest.restaurantName;
		req.phone = rest.getPhone();
		req.streetName = rest.streetName;
		req.city = rest.getCity();
		req.website = rest.getWebsite();
		req.image = rest.getImage();
		req.description = rest.getDescription();
		req.businessHour = rest.getBusinessHour();
		req.categoryCode = rest.getCategoryCode();
		req.reservation = false;
		req.takeOut = false;
		String error = "<ul><li>This field is required.</li></ul>";
		if (req.restaurantName.compareTo("") == 0
				|| req.phone.compareTo("") == 0
				|| req.streetName.compareTo("") == 0
				|| req.city.compareTo("") == 0
				|| req.description.compareTo("") == 0
				|| req.businessHour.compareTo("") == 0
				|| Integer.toString(req.categoryCode).compareTo("") == 0) {
			if (req.restaurantName.compareTo("") == 0) {
				model.addAttribute("restaurantName", error);
			}
			if (req.phone.compareTo("") == 0) {
				model.addAttribute("phone", error);
			}
			if (req.streetName.compareTo("") == 0) {
				model.addAttribute("streetName", error);
			}
			if (req.city.compareTo("") == 0) {
				model.addAttribute("city", error);
			}
			if (req.description.compareTo("") == 0) {
				model.addAttribute("description", error);
			}
			if (req.businessHour.compareTo("") == 0) {
				model.addAttribute("businessHour", error);
			}
			if (Integer.toString(req.categoryCode).compareTo("") == 0) {
				model.addAttribute("categoryCode", error);
			}
			model.addAttribute("RestaurantName", req.getRestaurantName());
			model.addAttribute("Phone", req.getPhone());
			model.addAttribute("StreetName", req.getStreetName());
			model.addAttribute("City", req.getCity());
			model.addAttribute("Description", req.getDescription());
			model.addAttribute("BusinessHour", req.getBusinessHour());
			model.addAttribute("CategoryCode", req.getCategoryCode());
			model.addAttribute("Website", req.getWebsite());
			model.addAttribute("Image", req.getImage());
			model.addAttribute("catList", DataManager.getCategoryList());
			return "restaurantAdd";
		} else {
			if (req.image.compareTo("") == 0) {
				req.image = "/VancouverTongue/static/defaultRestaurant.png";
			}
			if (account.level >= 3) {
				DataManager.editRestaurant(req);
				alertBox = "<script>alert('RESTAURANT HAS SUCCESSFULLY BEEN ADDED')</script>";
				session.setAttribute("alertBox", alertBox);
			} else {
				req.editBy = account.getUserId();
				req.actId = 1;
				DataManager.addRequest(req);
				alertBox = "<script>alert('REQUEST HAS BEEN SENT TO OUR STAFF, PLEASE WAIT')</script>";
				session.setAttribute("alertBox", alertBox);

			}
			return "redirect:/index";
		}
	}

	/**
	 * go to "restaurantAdd.jsp"
	 * 
	 * @param session
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/addRestaurant", method = RequestMethod.GET)
	public String addRestaurant(HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		model.addAttribute("catList", DataManager.getCategoryList());
		Helper.lastVisit(request, session);
		Account account = (Account) session.getAttribute("account");
		if (account == null) {
			Helper.errorMessage(session, "No authorization",
					"Please log in first!");
			return GO_ERROR;
		} else {
			return "restaurantAdd";
		}
	}

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public String search(HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {

		Helper.lastVisit(request, session);
		model.addAttribute("catList", DataManager.getCategoryList());
		model.addAttribute("RandomRest", DataManager.getRandomRestaurant());

		return "search";
	}

	/**
	 * Search restaurants:
	 * 
	 * @param s
	 * @param session
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/search/temp", method = RequestMethod.GET)
	public String searchTemp(Search s, HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Search search = new Search();

		// Helper.lastVisit(request, session);

		search.setCategoryCode(s.getCategoryCode());
		search.setCity(s.getCity());
		search.setName(s.getName());
		Restaurant rest[] = DataManager.searchRestaurant(search);
		model.addAttribute("resultList", rest);
		model.addAttribute("catList", DataManager.getCategoryList());
		model.addAttribute("code", new Integer(s.getCategoryCode()));
		model.addAttribute("name", s.getName());
		model.addAttribute("city", s.getCity());
		model.addAttribute("RandomRest", DataManager.getRandomRestaurant());
		return "search";
	}

	/**
	 * Browse all restaurant
	 * 
	 * @param session
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/browse", method = RequestMethod.GET)
	public String browse(HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Helper.lastVisit(request, session);
		model.addAttribute("resultList", DataManager.getAllRestaurant());
		model.addAttribute("RandomRest", DataManager.getRandomRestaurant());
		return "browse";
	}

	/**
	 * Go to ADMIN page:
	 * 
	 * @param session
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/admin", method = RequestMethod.GET)
	public String admin(HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Helper.lastVisit(request, session);
		Account account = (Account) session.getAttribute("account");
		if (account == null || account.level != 3) {
			Helper.errorMessage(session, "No authorization",
					"No authorization detacted! Please contact administrators.");
			return GO_ERROR;
		} else {
			return "admin";
		}
	}

	@RequestMapping(value = "/admin/block", method = RequestMethod.GET)
	public String block(HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Helper.lastVisit(request, session);
		Account account = (Account) session.getAttribute("account");
		if (account == null || account.level != 3) {
			Helper.errorMessage(session, "No authorization",
					"No authorization detacted! Please contact administrators.");
			return GO_ERROR;
		} else {
			return "block";
		}
	}

	@RequestMapping(value = "/admin/block/temp", method = RequestMethod.GET)
	public String block(String userId, String days, String message,
			HttpSession session, Model model, HttpServletRequest request)
			throws SQLException {

		Account check = (Account) session.getAttribute("account");

		if (check == null) {
			Helper.errorMessage(session, "No authorization",
					"Please log in first");
			return GO_ERROR;
		} else if (check.level < 3) {
			Helper.errorMessage(session, "No authorization",
					"Your account level is not able to do this function");
			return GO_ERROR;
		}

		Account user;
		Account account = (Account) session.getAttribute("account");
		String blockBy = account.getUserId();
		String USERID = "";
		String DAYS = "";
		int day = 0;
		if (userId.compareTo("") == 0 || days.compareTo("") == 0) {
			if (userId.compareTo("") == 0) {
				USERID = "<ul><li>Who to block: *</ul></li>";
			}
			if (days.compareTo("") == 0) {
				DAYS = "<ul><li>How many days to block the user: *</ul></li>";
			}
			model.addAttribute("USERID", USERID);
			model.addAttribute("DAYS", DAYS);
			model.addAttribute("UserId", userId);
			model.addAttribute("Days", days);
			return "block";
		}
		// convert string to int
		try {
			day = Integer.parseInt(days);
		} catch (Exception e) {
			e.printStackTrace();
			DAYS = "<ul><li>Please enter an integer: *</ul></li>";
			model.addAttribute("UserId", userId);
			model.addAttribute("DAYS", DAYS);
			return "block";
		}
		if (day < 0) {
			DAYS = "<ul><li>Enter a positive integer: *</ul></li>";
			model.addAttribute("DAYS", DAYS);
			model.addAttribute("UserId", userId);
			return "block";
		}
		user = DataManager.getAccountByUserId(userId);
		if (user == null) {
			model.addAttribute("Days", days);
			model.addAttribute("UserId", userId);
			USERID = "<ul><li>***No such ID!***</ul></li>";
			model.addAttribute("USERID", USERID);
			return "block";
		}
		// if level is equal or lower:
		if (user.getLevel() >= account.getLevel()) {
			Helper.errorMessage(
					session,
					"No Block Authorization",
					"Your account level is not high enough to block "
							+ account.getUserId() + ".");
			return GO_ERROR;
		} else {
			DataManager.blockAccount(userId, blockBy, day, message);
			String ALERT = "<script>alert('Successfully block user: "
					+ user.getUserId() + "');</script>";
			model.addAttribute("ALERT", ALERT);
			return "block";
		}
	}

	// @RequestMapping(value = "/{name}.png", method = RequestMethod.GET)
	// public String test(@PathVariable String name,HttpServletRequest r){
	// System.out.println(r.getRequestURL());
	// return "redirect:/static/"+name+".png";
	// }

	@RequestMapping(value = "/admin/block/searchprofile/temp", method = RequestMethod.GET)
	public String searchProfile(HttpSession session, String userId,
			Model model, HttpServletRequest request) throws SQLException {
		Account account = (Account) session.getAttribute("account");

		if (account == null) {
			Helper.errorMessage(session, "No authorization",
					"Please log in first");
			return GO_ERROR;
		} else if (account.level < 3) {
			Helper.errorMessage(session, "No authorization",
					"Your account level is not able to do this function");
			return GO_ERROR;
		}

		Account arr[];
		String info = "";
		if (userId.compareTo("") == 0) {
			arr = DataManager.GetAllAccount();
		} else {
			arr = new Account[1];
			arr[0] = DataManager.getAccountByUserId(userId);
			if (arr[0] == null) {
				info = "No such user";
			}
		}
		model.addAttribute("SEARCHINFO", info);
		model.addAttribute("arrList", arr);

		return "block";
	}

	/**
	 * Action on restaurant request:
	 * 
	 * @param session
	 * @param userId
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/admin/restaurantRequest", method = RequestMethod.GET)
	public String restaurantRequest(HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Helper.lastVisit(request, session);
		Account account = (Account) session.getAttribute("account");
		if (account == null) {
			Helper.errorMessage(session, "No authorization",
					"Please log in first");
			return GO_ERROR;
		} else if (account.level < 3) {
			Helper.errorMessage(session, "No authorization",
					"Your account level is not able to do this function");
			return GO_ERROR;
		}
		model.addAttribute("discardInfo", session.getAttribute("discardInfo"));
		model.addAttribute("confirmInfo", session.getAttribute("confirmInfo"));
		session.removeAttribute("confirmInfo");
		session.removeAttribute("discardInfo");

		ArrayList<RestaurantRequest> newReq = new ArrayList();
		ArrayList<RestaurantRequest> editReq = new ArrayList();
		RestaurantRequest[] arrList = DataManager.getAllRequest();
		String noAddRequest = "";
		String noEditRequest = "";

		if (arrList != null) {
			for (int i = 0; i < arrList.length; i++) {
				// new request:
				if (arrList[i].actId == 1) {
					newReq.add(arrList[i]);
				}
				// edit request:
				if (arrList[i].actId == 2) {
					editReq.add(arrList[i]);
				}
			}

			if (newReq.size() == 0) {
				noAddRequest = "<ul><li>Currently no request: </ul></li>";
			}
			if (editReq.size() == 0) {
				noEditRequest = "<ul><li>Currently no request: </ul></li>";
			}
		}

		model.addAttribute("noAddRequest", noAddRequest);
		model.addAttribute("noEditRequest", noEditRequest);
		model.addAttribute("newReq", newReq);
		model.addAttribute("editReq", editReq);

		return "restaurantReq";
	}

	/**
	 * View a single page of one request
	 * 
	 * @param id
	 * @param session
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/admin/request/{id}", method = RequestMethod.GET)
	public String viewRequest(@PathVariable int id, HttpSession session,
			Model model, HttpServletRequest request) throws SQLException {
		Account account = (Account) session.getAttribute("account");
		Helper.lastVisit(request, session);
		if (account == null) {
			Helper.errorMessage(session, "No authorization",
					"Please log in first");
			return GO_ERROR;
		} else if (account.level < 3) {
			Helper.errorMessage(session, "No authorization",
					"Your account level is not able to do this function");
			return GO_ERROR;
		}
		RestaurantRequest req = DataManager.getOneRequest(id);
		if (req.actId == 2) {
			Restaurant rest = DataManager
					.getRestByRestId(req.getRestaurantId());
			model.addAttribute("original", rest);
		}
		model.addAttribute("restaurant", req);
		return "request";
	}

	@RequestMapping(value = "/admin/request/{requestId}/discard", method = RequestMethod.POST)
	public String discardRequest(@PathVariable int requestId,
			HttpSession session, Model model, HttpServletRequest request)
			throws SQLException {
		Account account = (Account) session.getAttribute("account");

		if (account == null) {
			Helper.errorMessage(session, "No authorization",
					"Please log in first");
			return GO_ERROR;
		} else if (account.level < 3) {
			Helper.errorMessage(session, "No authorization",
					"Your account level is not able to do this function");
			return GO_ERROR;
		}

		DataManager.disgardOneRequest(requestId);
		String alertBox = "";
		alertBox = "<script>alert('Restaurant request has been discarded')</script>";
		session.setAttribute("discardInfo", alertBox);

		return "redirect:/admin/restaurantRequest";
	}

	@RequestMapping(value = "/admin/request/{requestId}/confirm", method = RequestMethod.POST)
	public String confirmRequest(@PathVariable int requestId,
			HttpSession session, Model model, HttpServletRequest request)
			throws SQLException {
		Account account = (Account) session.getAttribute("account");

		if (account == null) {
			Helper.errorMessage(session, "No authorization",
					"Please log in first");
			return GO_ERROR;
		} else if (account.level < 3) {
			Helper.errorMessage(session, "No authorization",
					"Your account level is not able to do this function");
			return GO_ERROR;
		}
		DataManager.executeRequest(requestId);
		String alertBox = "";
		alertBox = "<script>alert('Restaurant has been successfully added')</script>";
		session.setAttribute("confirmInfo", alertBox);
		return "redirect:/admin/restaurantRequest";
	}

//	@RequestMapping(value = "/upload", method = RequestMethod.GET)
//	public String uploadGet(HttpSession session, Model model,
//			HttpServletRequest request) throws SQLException {
//		Helper.lastVisit(request, session);
//		model.addAttribute("resultList", DataManager.getAllRestaurant());
//
//		return "upload";
//	}

//	@RequestMapping(value = "/upload", method = RequestMethod.POST)
//	public String create(UploadItem uploadItem, BindingResult result,
//			HttpServletRequest request, HttpServletResponse response,
//			HttpSession session) {
//
//		// Some type of file processing...
//		System.err.println("-------------------------------------------");
//		try {
//			MultipartFile file = uploadItem.getFileData();
//			String fileName = null;
//			InputStream inputStream = null;
//			OutputStream outputStream = null;
//			if (file.getSize() > 0) {
//				inputStream = file.getInputStream();
//				if (file.getSize() > 1000000) {
//					System.out.println("File Size:::" + file.getSize());
//					return "/uploadfile";
//				}
//				System.out.println("size::" + file.getSize());
//				fileName = request.getRealPath("") + File.separator + "static"
//						+ File.separator + file.getOriginalFilename();
//				System.out.println("fileName:" + fileName);
//				File f = new File(fileName);
//				if (!f.exists()) {
//					f.createNewFile();
//				}
//				outputStream = new FileOutputStream(f);
//				System.out.println("fileName:" + file.getOriginalFilename());
//
//				int readBytes = 0;
//				byte[] buffer = new byte[10000];
//				while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
//					outputStream.write(buffer, 0, readBytes);
//				}
//				outputStream.close();
//				inputStream.close();
//			}
//
//			// ..........................................
//			session.setAttribute("uploadFile", file.getOriginalFilename());
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return "uploadSuccess";
//	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register(HttpSession session, Model model,
			HttpServletRequest request) throws SQLException {
		Helper.lastVisit(request, session);
		return "register";
	}

	/**
	 * Register temp page
	 * 
	 * @param session
	 * @param userId
	 * @param password
	 * @param passwordRep
	 * @param email
	 * @param description
	 * @param model
	 * @param request
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/register/temp", method = RequestMethod.POST)
	public String registerTemp(HttpSession session, String userId,
			String password, String passwordRep, String email,
			String description, Model model, HttpServletRequest request)
			throws SQLException {
		String error = "<ul><li>This field is required: </ul></li>";
		String alertBox = "";
		if (userId.compareTo("") == 0 || password.compareTo("") == 0
				|| passwordRep.compareTo("") == 0
				|| password.compareTo(passwordRep) != 0
				|| DataManager.checkAccId(userId) == true) {
			if (userId.compareTo("") == 0) {
				model.addAttribute("USERID", error);
			}
			if (password.compareTo("") == 0) {
				model.addAttribute("PASSWORD", error);
			}
			if (passwordRep.compareTo("") == 0) {
				model.addAttribute("PASSWORDREP", error);
			}
			if (password.compareTo(passwordRep) != 0) {
				alertBox = "<script>alert('Passwords are not identical')</script>";
			}
			if (DataManager.checkAccId(userId) == true) {
				alertBox = "<script>alert('" + userId
						+ " already exists, please use a new one')</script>";
			}
			model.addAttribute("AlertBox", alertBox);
			model.addAttribute("UserId", userId);
			model.addAttribute("Email", email);
			model.addAttribute("Description", description);

			return "register";
		} else {
			Account account = new Account();
			account.userId = userId;
			account.password = password;
			account.description = description;
			account.email = email;
			account.avatar = "/VancouverTongue/static/defaultAvator.gif";
			account.level = 1;
			String successful = "<script>alert('Successfully registered')</script>";
			session.setAttribute("account", account);
			session.setAttribute("registerSucc", successful);
			DataManager.createUserAcc(account);
			return "redirect:/";
		}
	}

	@RequestMapping(value = "/restaurant/{id}/delete", method = RequestMethod.GET)
	public String deleteRestaurant(@PathVariable int id, HttpSession session)
			throws SQLException {
		Account account = (Account) session.getAttribute("account");
		if (account != null && account.level >= 3) { // OK
			DataManager.deleteOneRestaurant(id);
			return "redirect:/";
		}
		Helper.errorMessage(session, "No authen", "sdfsdf");
		return GO_ERROR;

	}

}